const sequelize = require('./database')
const logger = require('../utils/logger')
const bcrypt = require('bcryptjs')

// 导入所有模型
const User = require('../models/user')
const Department = require('../models/department')
const Role = require('../models/role')
const UserDepartment = require('../models/userDepartment')
const UserThirdParty = require('../models/userThirdParty')
const PermissionTemplate = require('../models/PermissionTemplate')
const UserPermission = require('../models/userPermission')
const DepartmentPermission = require('../models/departmentPermission')
const RolePermission = require('../models/rolePermission')
const SystemConfig = require('../models/SystemConfig')
const Admin = require('../models/Admin')
const Certificate = require('../models/Certificate')
const Field = require('../models/Field')
const ImportExportRecord = require('../models/importExportRecord')

async function dropTables() {
  try {
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 0')
    
    // 按照依赖关系顺序删除表（从最底层的依赖开始删除）
    const tables = [
      'import_export_records',
      'user_third_parties',
      'user_departments',
      'user_permissions',
      'role_permissions',
      'department_permissions',
      'users',
      'roles',
      'departments',
      'permission_templates',
      'certificates',
      'fields',
      'admins',
      'system_config'
    ]
    
    for (const table of tables) {
      try {
        await sequelize.query(`DROP TABLE IF EXISTS ${table}`)
        logger.info(`表 ${table} 删除成功`)
      } catch (err) {
        logger.warn(`表 ${table} 删除失败: ${err.message}`)
      }
    }
    
    await sequelize.query('SET FOREIGN_KEY_CHECKS = 1')
    logger.info('所有表删除完成')
  } catch (error) {
    logger.error('删除表失败:', error)
    throw error
  }
}

async function createTables() {
  try {
    // 按照依赖关系顺序创建表
    const models = [
      SystemConfig,
      Admin,
      Field,
      Certificate,
      PermissionTemplate,
      Department,
      Role,
      User,
      UserDepartment,
      UserThirdParty,
      UserPermission,
      RolePermission,
      DepartmentPermission,
      ImportExportRecord
    ]

    // 逐个同步模型，避免外键约束问题
    for (const model of models) {
      await model.sync({ alter: true })
      logger.info(`表 ${model.tableName} 创建/更新完成`)
    }

    logger.info('所有数据库表创建/更新完成')
  } catch (error) {
    logger.error('创建/更新表失败:', error)
    throw error
  }
}

async function createDefaultAdmin() {
  try {
    const adminExists = await Admin.findOne({ where: { username: 'admin' } })
    if (!adminExists) {
      const adminPassword = process.env.ADMIN_PASSWORD || 'admin123'
      await Admin.create({
        username: 'admin',
        name: '系统管理员',
        password: adminPassword,
        status: 1
      })
      logger.info('默认管理员账号创建成功')
    }
  } catch (error) {
    logger.error('创建默认管理员账号失败:', error)
    throw error
  }
}

async function initDatabase() {
  try {
    const shouldResetDB = process.env.RESET_DB === 'true'
    
    if (shouldResetDB) {
      // 重置模式：删除所有表并重新创建
      logger.info('开始重置数据库...')
      await dropTables()
      await createTables()
      
      // 创建系统预设数据
      await PermissionTemplate.createSystemTemplates()
      logger.info('系统预设权限模板创建完成')

      // 创建系统预设角色
      await Role.createSystemRoles()
      logger.info('系统预设角色创建完成')
      
      // 创建默认管理员账号
      await createDefaultAdmin()
      
      logger.info('数据库重置完成')
    } else {
      // 正常模式：只同步表结构
      await createTables()
      
      // 确保默认管理员账号存在
      await createDefaultAdmin()
    }

  } catch (error) {
    logger.error('数据库初始化失败:', error)
    throw error
  }
}

module.exports = initDatabase 